<?php
/**
 * 贷款档位model
 */
namespace app\v2\model;
use think\Db;
use think\Model;
class Gear extends Model {

	protected $name = 'gear';
	protected $createTime = 'time';
	protected $updateTime = false;
	protected $autoWriteTimestamp = 'datetime';

		/**
		 * 所有卡片
		 * @author   yhq <934797303@qq.com>
		 * @DateTime 2017-07-26 11:40
		 * @param    string $uid       用户id
		 * @param    array  $open_gid  我解锁的卡
		 * @param    array  $card      所有档位卡
		 * @return   json                    
		 */
		public function card($uid){
			$open_gid = Db::name('user_info')->where('uid', $uid)->value('open_gid');
			$open_gid = json_decode($open_gid,true);
			$card = $this->where('status', '1')->field('create_time,update_time',true)->order('money')->select();
			$card = modelo2array($card);
			foreach ($card as $key => $value) {
				$card[$key]['lock'] = 1;
				if($uid){
						$card[0]['lock'] = 0;  //默认解锁第一张卡
				}
				if(!is_null($open_gid)&&in_array($card[$key]['id'],$open_gid)){
					$card[$key]['lock'] = 0;  //解锁卡片
				}
			}
			return  $card;
		}
		
		/**
		 * 贷款档位
		 * @author   yhq <934797303@qq.com>
		 * @DateTime 2017-07-26 11:40
		 * @param    string $uid       用户id
		 * @param    array  $open_gid  我解锁的卡
		 * @param    array  $gear      所有档位卡
		 * @return   json                    
		 */
		public function gear($uid){
			$userInfoModel = new UserInfo();
			$userInfo = $userInfoModel->where('uid', $uid)->find();

			// if(empty($userInfo['open_gid'])){
			// 	$gear = $this->where('status',1)->order('money')->select();
			// 	if(!$gear) {
			// 		$this->error = '系统错误';
			// 		return false;
			// 	}
			// 	$gid = $gear[0]['id'];
			// 	$open_gid = array($gid);  //默认解锁金额最小的卡片
			// }else{
			// 	$open_gid = json_decode($userInfo['open_gid'],true); //解锁的卡片
			// }

			// $arr_money = array();
			// foreach ($open_gid as $value) {
			// 	$arr_money[] = $this->where('id', $value)->value('money');
			// }
			// sort($arr_money);
			// $max_money = end($arr_money);  //可申请最大总金额

			# 2017-12-22  获取可申请最大总金额
			if(empty($userInfo['max_money'])){
				$config = Db::name('config')->order('money')->field('money')->find();
				$userInfo['max_money'] = $config['money'];
			}
			$max_money = $userInfo['max_money'];
			
			$where['money'] = array('elt', $max_money);
			$sort = Db::name('config')->where($where)->field('id, money, period')->order('money')->select();
			if(empty($sort)){
				$this->error = '没有额度';
				return false;
			}
			$tmpArr = array();
			foreach ($sort as $key => $value) {
				if(in_array($value['money'], $tmpArr)){
					continue;
				}
				$tmpArr[] = $value['money'];
			}
			$list = array();
			foreach ($tmpArr as $key => $value) {
				$list[$key]['value'] = formatMoney($value);
			}
			foreach ($list as $key => $value) {
				foreach ($sort as $k => $v) {
					if($v['money']==$value['value']){
						$tmp = ['id'=>$v['id'],'value'=>$v['period']];
						$list[$key]['child'][] = $tmp;
						$list[$key]['child'] = $this->bubble_sort($list[$key]['child'],'value');
						unset($tmp);
					}
				}
			}

			//构建返回数组
			$result = array(
				'list'       => $list, //挡位列表
				'date'       => '',    //约定还款时间
				'money'      => '0',   //还款金额
				'progress'   => '0',   //还款进度
				'has_reloan' => '0',   //是否有一键借款
				'has_bank'   => '0',   //是否验证银行卡
				'id_card'    => '',    //身份证后6位
				'status'     => '1',   //状态
				'info'       => '立即拿钱',    //按钮文字信息
			);

			$applyModel = new Apply();
			$apply = $applyModel->where(['uid'=>$uid])->order('id desc')->find(); //上次借款单
			if($apply){
				$result['date']  = $applyModel->loanMoney($apply)['appoint_time'];
				$result['money'] = $applyModel->loanMoney($apply)['money_order'];
				//还款进度
				$now = date('Y-m-d',SYS_TIMESTAMP);
				$appoint_time = $result['date'];
				$period       = $apply['period'];  //借款周期
				$day = (strtotime($now)-strtotime($appoint_time))/(24*3600);
				if($day>0){  //逾期
					$result['progress'] = '100';
				}else{
					$result['progress'] = ceil(($period-abs($day))/$period*100);
				}
				//是否有一键借款
				if($apply['hk_time']&&$apply['status']==5){
					$lastTime = (SYS_TIMESTAMP-strtotime($apply['hk_time']))/(24*3600);
					if($lastTime<7){ //上次还款时间小于七天 可一键借款
						$result['has_reloan'] = '1';
					}
				}
				//借款单状态
				$result['status'] = self::apply_status($apply)['status'];
				$result['info']   = self::apply_status($apply)['info'];
			}
			//银行卡、身份证
			$result['has_bank'] = empty($userInfo['bank_card_number']) ? '0' : '1';
			// $result['id_card']  = substr($userInfo['id_card'],-6);

			return  $result;
		}


		/**
		 * 数组排序
		 * @param  array  $sort 数组
		 * @param  string $a    排序字段
		 * @param  string $type 排序规则
		 * @return array        排序后的数组
		 */
		public function bubble_sort($sort,$a,$type='asc'){//默认为正序排列  
				$tmpArr = array();
				$len = count($sort);
				 if($type=='asc'){  
						for ($i=0; $i < $len-1; $i++) { 
								for ($j=$len-1; $j > $i; --$j) { 
										 if($sort[$j][$a]<$sort[$j-1][$a]){
												$tmpArr=$sort[$j];
												$sort[$j]=$sort[$j-1];
												$sort[$j-1]=$tmpArr;
										 }
								}
						}
				 }else{
						for ($i=0; $i < $len-1; $i++) { 
								for ($j=$len-1; $j > $i; --$j) { 
										 if($sort[$j][$a]>$sort[$j-1][$a]){
												$tmpArr=$sort[$j];
												$sort[$j]=$sort[$j-1];
												$sort[$j-1]=$tmpArr;
										 }
								}
						}
				 }
				return $sort;  
		}

		/**
		 * 申请状态
		 * @author   yhq <934797303@qq.com>
		 * @DateTime 2017-08-04T14:53:51+0800
		 * @param    int      $uid  用户id
		 * @return   array    状态数组
		 */
		public function apply_status($apply) {
			$data['status'] = 1;
			$data['info']   = '立即拿钱';
			$data['part']   = 0; //部分还款

			if(!empty($apply)){
				$status = $apply['status'];

				if(in_array($status, [0,1,2,9])){
					$data['status'] = 2;
					$data['info'] = '查看结果';  //申请成功
				}
				if(in_array($status, [3,4,12])){
					$data['status'] = 3;
					$data['info'] = '我要还款';
				}

				$applyModel = new Apply;
				if($applyModel->rejectCanApply($apply['uid'])){
					# 用户自动放弃后可以立即申请
					$data['status'] = 1;
					$data['info'] = '立即拿钱';
				}else{
					# 借款失败后未到可申请时间不能申请
					$countdown = $applyModel->countdown($apply['uid']);
					if($countdown && SYS_TIMESTAMP< strtotime($countdown['endTime'])){
						$data['status'] = 4;
						$data['info'] = '查看结果';  //审核不通过
					}
				}

				#可以部分还款
				if($status==4) {
					$data['part']   = 1; //部分还款
				}
			}

			return $data;
		}

	}
